package de.karlNet.login.attributeMapper;

import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;

import org.springframework.stereotype.Component;

import de.karlNet.sambamanager.ldapModel.LdapComputer;
import de.karlNet.sambamanager.ldapModel.LdapDomainController;
import de.karlNet.sambamanager.ldapModel.LdapObject;

@Component
public class ComputerExtractor extends LdapObjectExtractor {

	private LdapDomainController getLdapDomainController(Attributes attributes)
			throws NamingException {
		String dn = this.tryToGetString("distinguishedname", attributes,
				tryToGetString("dn", attributes));
		String cn = this.tryToGetString("name", attributes,
				tryToGetString("samaccountname", attributes));
		String operatingSystem = this.tryToGetString("operatingSystem",
				attributes);
		String operatingSystemVersion = this.tryToGetString(
				"operatingSystemVersion", attributes);
		String dnsName = this.tryToGetString("dNSHostName", attributes);
		return new LdapDomainController(dn, cn, operatingSystem,
				operatingSystemVersion, dnsName);
	}

	private LdapComputer getLdapComputer(Attributes attributes)
			throws NamingException {
		String dn = this.tryToGetString("distinguishedname", attributes,
				tryToGetString("dn", attributes));
		String cn = this.tryToGetString("name", attributes,
				tryToGetString("samaccountname", attributes));
		return new LdapComputer(dn, cn);
	}

	@Override
	public LdapObject extract(Attributes attributes, List<String> objectClasses)
			throws NamingException {
		if (objectClasses.contains("computer")) {
			int accountControl = Integer.parseInt(this.tryToGetString(
					"userAccountControl", attributes));
			if ((accountControl & 8192) == 8192) {
				return this.getLdapDomainController(attributes);
			}
			return this.getLdapComputer(attributes);
		}
		return null;
	}

}
